<?php

namespace app\shop\controller;

use app\common\model\admin\AccountStoreModel;
use app\common\model\jiyun\base\ChannelModel;
use app\common\model\jiyun\warehouse\WarehouseModel;
use app\common\model\shop\GoodsModel;
use app\common\model\shop\OrderInfoModel;
use app\common\model\shop\OrderModel;
use app\common\model\shop\OrderRemarkModel;
use app\common\model\shop\PlatformModel;
use app\common\model\shop\ShopsModel;
use app\shop\service\SyncOrderService;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\admin\model\SystemUser;
use think\facade\Validate;

/**
 * 订单列表
 *
 * @Description 订单列表
 * @package app\shop\controller
 * @author Lihongqi
 * @date 2024-10-17 10:55
 */
class Order extends Controller
{
    /**
     * 订单列表
     * @auth true
     * @menu true
     * @author Lihongqi
     * @date 2024-10-17 13:37
     */
    public function index ()
    {
        OrderModel::mQuery()->layTable(function () {
            $this->title = '订单列表';

            // 获取平台列表
            $this->platform_list = PlatformModel::mk()->where('status', 1)->column('title', 'id');
            // 获取订单状态组合
            $this->status_arr = OrderModel::getStatusName();
            // 获取平台下的店铺
            $map = [
                ['is_deleted',  '=', 0]
            ];
            if(!$this->super){
                $map[] = ['user_id', '=', $this->adminUser['id']];
            }
            $this->shop_list = ShopsModel::mk()->where($map)->column('name', 'id');
            // 订单推送状态
            $this->sync_status_arr = OrderModel::getSyncStatus();

        }, function (QueryHelper $query) {

            $this->check_user = false;
            $query->like('buy_user,buy_mobile')->equal('account_id,platform_id,order_no,order_number,status#type,shop_id,sync_status')->dateBetween('order_time,delivery_time');
            $query->order('id desc');
        });
    }


    protected function _index_page_filter (&$data)
    {
        // 获取平台信息
        $platform_ids = array_column($data, 'platform_id');
        $platform_arr = [];
        if(!empty($platform_ids)){
            $map = [
                ['id', 'in', $platform_ids],
            ];
            $platform_arr = PlatformModel::mk()->where($map)->column('title', 'id');
        }
        // 获取订单状态
        $status_arr = OrderModel::getStatusName();
        // 获取店铺信息
        $shop_ids = array_column($data, 'shop_id');
        $shop_arr = [];
        if(!empty($shop_ids)){
            $map = [
                ['id', 'in', $shop_ids],
            ];
            $shop_arr = ShopsModel::mk()->where($map)->column('name', 'id');
        }
        // 获取订单集运推送状态
        $sync_status_arr = OrderModel::getSyncStatus();

        foreach ($data as &$item) {
            $item['platform_name'] = $platform_arr[$item['platform_id']] ?? '';
            $item['status_name'] = !empty($status_arr[$item['status']]) ? $status_arr[$item['status']] : '';
            $item['shop_name'] =  !empty($shop_arr[$item['shop_id']]) ? $shop_arr[$item['shop_id']] : '';
            $item['sync_status_name'] = $sync_status_arr[$item['sync_status']] ?? '';
        }
    }

    /**
     * 订单详情
     * @auth true
     * @menu true
     * @author Lihongqi
     * @date 2024-10-17 13:37
     */
    public function info ()
    {

        $this->order_id = $this->request->get('id');
        $this->order_detail = OrderModel::mk()->where('id', $this->order_id)->find();
        // 获取平台信息
        $platform_name = PlatformModel::mk()->where('id', $this->order_detail['platform_id'])->value('title');
        // 获取店铺信息
        $shop_name = ShopsModel::mk()->where('id', $this->order_detail['shop_id'])->value('name');
        // 获取订单状态
        $status_arr = OrderModel::getStatusName();
        $status_name = !empty($status_arr[$this->order_detail['status']]) ? $status_arr[$this->order_detail['status']] : '';
        $this->base_info = [
            ['title'    =>  '平台', 'value' => $platform_name],
            ['title'    =>  '店铺', 'value' => $shop_name],
            ['title'    =>  '订单状态', 'value' => $status_name],
            ['title'    =>  '平台订单状态', 'value' => $this->order_detail['status_msg']],
            ['title'    =>  '订单ID', 'value' => $this->order_detail['order_no']],
            ['title'    =>  '下单时间', 'value' => $this->order_detail['order_time']],
            ['title'    =>  '买家姓名', 'value' => $this->order_detail['user_name']],
            ['title'    =>  '买家电话', 'value' => $this->order_detail['user_mobile']],
            ['title'    =>  '绑定采购单号', 'value' => $this->order_detail['other_order_no']],
        ];
        // 获取订单详情货币
        $currency_code  = OrderInfoModel::mk()->where('order_id', $this->order_id)->value('money_unit');
        $this->payment_info = [
            ['title'    =>  '订单金额', 'value' => $this->order_detail['pay_money']],
            ['title'    =>  '产品金额', 'value' => $this->order_detail['total_price'].' '.$currency_code],
            ['title'    =>  '运费金额', 'value' => $this->order_detail['freight_money']],
            ['title'    =>  '税金', 'value' => 0],
            ['title'    =>  '优惠金额', 'value' => $this->order_detail['discount_money']],
            ['title'    =>  '币种', 'value' => $this->order_detail['money_unit']],
            ['title'    =>  '付款方式', 'value' => $this->order_detail['pay_way']],
        ];
        $this->user_address = [
            ['title'    =>  '收件人', 'value' => $this->order_detail['user_name']],
            ['title'    =>  '电话/手机', 'value' => $this->order_detail['user_mobile']],
            ['title'    =>  '国家/地区', 'value' => $this->order_detail['country']],
            ['title'    =>  '省/州', 'value' => $this->order_detail['user_region']],
            ['title'    =>  '城市', 'value' => $this->order_detail['user_city']],
            ['title'    =>  '区县', 'value' => $this->order_detail['user_district']],
            ['title'    =>  '邮编', 'value' => $this->order_detail['zip_code']],
            ['title'    =>  '地址', 'value' => $this->order_detail['user_address']],
        ];
        // 设置订单进程
        switch ($this->order_detail['status']) {
            case OrderModel::STATUS_CANCEL:// 取消订单
                $this->progress_status_arr = [OrderModel::STATUS_CONFIRM => '已下单', OrderModel::STATUS_CANCEL => '已取消'];
                break;
            case OrderModel::STATUS_WAIT:// 待发货
                $this->progress_status_arr = [OrderModel::STATUS_CONFIRM => '已下单', OrderModel::STATUS_WAIT => '待发货'];
                break;
            case OrderModel::STATUS_SEND:// 已发货
                $this->progress_status_arr = [OrderModel::STATUS_CONFIRM => '已下单', OrderModel::STATUS_WAIT => '待发货', OrderModel::STATUS_SEND => '已发货'];
                break;
            case OrderModel::STATUS_SIGN:// 已签收
                $this->progress_status_arr = [OrderModel::STATUS_CONFIRM => '已下单', OrderModel::STATUS_WAIT => '待发货', OrderModel::STATUS_SEND => '已发货', OrderModel::STATUS_SIGN => '已签收'];
                break;
            default:
                $this->progress_status_arr = [OrderModel::STATUS_CONFIRM => '已下单'];
                break;
        }
        $this->is_edit = ($this->order_detail['sync_status'] == OrderModel::SYNC_STATUS_YES) ? 0 : 1;
        OrderModel::mForm();
    }

    /**
     * 订单详情
     * @auth true
     * @author Lihongqi
     * @date 2024-10-17 13:37
     */
    public function infoList ()
    {
        $order_id = $this->request->get('order_id');

        $list = OrderInfoModel::mk()->where('order_id', $order_id)->select();

        // 获取订单主表
        $order_info = OrderModel::mk()->field('id,platform_id,shop_id,order_no,order_number')->where('id', $order_id)->find();
        // 获取平台信息
        list($goods_model, $sku_model, $attr_model, $image_model) = GoodsModel::instance( $order_info['platform_id']);
        $sku_ids_arr = !empty($list) ? array_column($list->toArray(), 'goods_nu') : [];
        $map = [
            ['goods_nu', 'in', $sku_ids_arr]
        ];
        $sku_list_data = $sku_model->where($map)->column('*', 'goods_nu');
        $goods_ids = array_column($sku_list_data, 'goods_id');
        $goods_data = [];
        if(!empty($goods_ids)){
            $map = [
                ['id', 'in', $goods_ids]
            ];
            $goods_data = $goods_model->where($map)->column('*', 'id');
        }

        foreach ($list as &$item) {
            $sku_info = !empty($sku_list_data[$item['goods_nu']]) ? $sku_list_data[$item['goods_nu']] : [];
            $goods_id = $sku_info['goods_id'] ?? 0;
            $goods_info = !empty($goods_data[$goods_id]) ? $goods_data[$goods_id] : [];
            $item->price_str     = $item->price.' '.$item->money_unit;
            $item->all_price_str    = round(($item->price * $item->num), 4).' '.$item->money_unit;
            $item->attr_title = !empty($sku_info['attribute_titles']) ? $sku_info['attribute_titles'] : '';
            $item->goods_url = isset($goods_info['source_url']) ? $goods_info['source_url'] : '';
            $item->goods_spu = isset($goods_info['spu_code']) ? $goods_info['spu_code'] : '';
            $item->main_pic = !empty($sku_info['image']) ? $sku_info['image'] : '';
        }

        $this->success('成功', $list, 0);
    }


    /**
     * 编辑数据
     *
     * @return void
     */
    public function editData()
    {
        $id    = $this->request->post('id');
        $value = $this->request->post('value');
        $field = $this->request->post('field');
        if(empty($value)){
            $this->error('修改信息不能为空');
        }

        $info_obj = OrderInfoModel::mk()->where('id', $id)->find();
        if(empty($info_obj)){
            $this->error('订单明细信息有误');
        }

        $info_obj->$field = $value;
        $info_obj->save();

        $this->success('修改成功');
    }

    /**
     * 订单详情
     * @auth true
     * @author Lihongqi
     * @date 2024-10-17 13:37
     */
    public function addressEdit ()
    {
        $id = $this->request->post('id');
        $user_name      = $this->request->post('user_name');
        $user_address   = $this->request->post('user_address');
        $user_mobile    = $this->request->post('user_mobile');
        $user_address_info = $this->request->post('user_address_info');


        $order_obj = OrderModel::mk()->where('id', $id)->find();

        $order_obj->user_name       = $user_name;
        $order_obj->user_address    = $user_address;
        $order_obj->user_mobile     = $user_mobile;
        $order_obj->user_address_info = $user_address_info;
        $order_obj->save();

        $this->success('成功');
    }

    /**
     * 添加备注
     *
     * @return void
     */
    public function addRemark ()
    {
        $this->user_id      = $this->adminUser['id'];
        $this->order_id     = $this->request->get('order_id');
        $this->remark_type   = OrderRemarkModel::getTypeName();
        OrderRemarkModel::mForm();
    }


    protected function _addRemark_form_result ($result, $data)
    {
        if ( $this->request->isPost() ) {
            $data['create_at'] = date("Y-m-d H:i:s");

            $data['user_name'] = SystemUser::mk()->where('id', $data['user_id'])->value('nickname');
            $data['type']      = $this->remark_type[$data['type']] ?? '';
            $this->success('成功', $data);
        }
    }

    /**
     * 同步订单
     * @auth true
     * @Description
     * @author wangqinghui
     * @date 2024-11-20 11:36
     * @return void
     */
    public function pullOrder()
    {
        if($this->request->isPost()){
            $post_data = $this->request->post();
            $rule = [
                'account_id|公司'    => 'require|integer|gt:0',
                'platform_id|平台'   => 'require|integer|gt:0',
            ];
            $validate = Validate::rule($rule);
            if (!$validate->check($post_data)) {
                $this->error($validate->getError());
            }
            $platform_id = $post_data['platform_id'];
            $platform_info = PlatformModel::mk()->where('id', $platform_id)->find();
            if(empty($platform_info)){
                $this->error('平台信息有误');
            }
            $shop_ids_str = '';
            $title = '异步拉取平台['.$platform_info['title'].']订单';
            $map = [
                ['account_id', '=', $post_data['account_id']],
                ['platform_id', '=', $platform_id],
                ['status', '=', 1]
            ];
            if(!empty($post_data['shop_id'])){
                $map[] = ['id', 'in', $post_data['shop_id']];
            }
            $shop_ids = ShopsModel::mk()->where($map)->column('id');
            if(!empty($shop_ids)){
                $shop_ids_str = implode(',', $shop_ids);
                $title .= ' 店铺ID:'.$shop_ids_str;
            }
            $this->_queue($title, 'orderpull '.$platform_info['code'].' '.$shop_ids_str);
        }else{
            $map = [
                ['status', '=', 1],
            ];
            $this->platform_list = PlatformModel::mk()->where($map)->column('title', 'id');
            $this->shop_account = $this->account_id;
            OrderModel::mForm();
        }
    }

    /**
     * 同步商品到集运
     *
     * @auth true
     * @Description
     * @return void
     */
    public function syncOrderTojy ()
    {

        if ( $this->request->isPost() ) {

            $order_ids = $this->request->post('order_ids');
            $shop_id   = $this->request->post('shop_id');
            // 仓库id
            $warehouse_id = $this->request->post('warehouse_id');
            // 渠道id
            $channel_id   = $this->request->post('channel_id');

            $order_ids    = explode(',', $order_ids);

            $channel_obj  = ChannelModel::mk()->with('country')->where('id', $channel_id)->find();
            $country_id   = $channel_obj->country->id;

            SyncOrderService::instance()->syncShopGoods ($shop_id,$order_ids,$warehouse_id,$channel_id,$country_id, $channel_obj->account_id);

            $this->success('成功');
        } else {


            $order_ids = $this->request->get('id');
            $shop_id   = $this->request->get('shop_id');


            //$edit_count = ShopOrderModel::mk()->whereIn('id', $order_ids)->where('sync_status', ShopOrderModel::SYNC_STATUS_YES)->count();

            $shop_id_arr = array_unique(explode(',', $shop_id));
            // 判断是否是同一家的订单
            if (count($shop_id_arr) > 1) {
                $this->error('只能推送 同一个商家的订单');
            }

            // 获得配置商家的仓库
            $warehouse_arr = AccountStoreModel::mk()->where('status', 1)->where('shop_id', $shop_id)->column('warehouse_id');

            if ( empty($warehouse_arr) ) {
                $this->error('请先设置合作仓储企业');
            }

            $warehouse_obj = WarehouseModel::mk()->whereIn('id', $warehouse_arr)->select();

            $channel_arr = [];

            $channel_ids_arr = explode(',',$warehouse_obj[0]['channel_ids']);

            $channel_obj= ChannelModel::mk()->with('country')->whereIn('id',$channel_ids_arr)->select();
            $channel_obj->each(function ($item) use (&$channel_arr) {
                $channel_arr[$item->id] =$item->title."({$item->country->coun_c_name})";
            });

            $this->warehouse_arr = $warehouse_obj->column('warehouse_c_name', 'id');
            $this->channel_arr   = $channel_arr;
            $this->order_ids     = $order_ids;
            $this->shop_id       = $shop_id;

            $this->fetch('sync');
        }

    }

    /**
     * 回填采购单号
     * @Description
     * @auth true
     * @author wangqinghui
     * @date 2024-12-06 11:36
     * @return void
     */
    public function editPurchaseOrder()
    {
        if($this->request->isPost()){

            $post_data = $this->request->post();
            $rule = [
                'order_id|订单号'   => 'require|integer|gt:0',
                'other_order_no|采购单号' => 'require|length:1,255'
            ];
            $validate = Validate::rule($rule);
            if(!$validate->check($post_data)) {
                $this->error($validate->getError());
            }

            $other_order_no_arr = explode("\n", $post_data['other_order_no']);
            if(empty($other_order_no_arr)){
                $this->error('采购单号信息有误');
            }
            // 校验单号是否被占用
            $map = [];
            foreach($other_order_no_arr as $value){
                $map[] = ['other_order_no', 'find in set', $value];
            }
            $exist_list = OrderModel::mk()->where('id', '<>', $post_data['order_id'])->where(function ($query) use($map){
                $query->whereOr($map);
            })->column('other_order_no');
            if(!empty($exist_list)){
                $exist_other_order_no_str = implode(',', $exist_list);
                $err_arr = array_intersect($other_order_no_arr, explode(',', $exist_other_order_no_str));
                $this->error('采购单号已被占用:'.implode('|', $err_arr));
            }
            $other_order_no = implode(',', $other_order_no_arr);
            // 更新订单数据
            $update_data = [
                'other_order_no' => $other_order_no,
            ];
            $count = OrderModel::mk()->where('id', $post_data['order_id'])->update($update_data);
           
            $this->success('绑定采购单成功');
        }else{
            $order_id = (int)$this->request->get('order_id');
            if(empty($order_id) || ($order_id <= 0)){
                $this->error('订单信息有误');
            }
            $order_info = OrderModel::mk()->where('id', $order_id)->find();
            $order_info->other_order_no = implode("\n", explode(',', $order_info->other_order_no));
            $this->fetch('edit_purchase_order', ['order_info' =>  $order_info]);
        }
    }
}